package com.joycessh.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

public class json_ed {
	/**
	 * 接受前端发送的json数据进行解析，得到json对象
	 * @param HttpServletRequest rq  
	 * @return JSONObject json对象
	 */
	public JSONObject json_decode(HttpServletRequest rq) {
		//获得request和response对象
		HttpServletRequest request = rq;
		String resStr = null;
		StringBuffer sb=new StringBuffer("");
		try {
			String line;
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
			while((line=br.readLine())!=null){
				sb.append(line);
			}
			br.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		resStr=sb.toString();
		return JSONObject.fromObject(resStr);
	}
	
	public void json_encode(HttpServletResponse response,JSONObject jsondata,String encoding) {
		response.setContentType("application/json;charset="+encoding);
		response.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter out = null;
		try {
			out = response.getWriter();
            out.write(jsondata.toString());
            out.flush();
            out.close();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}